package com.service.impl;

import com.dao.Td_tblPartyOrgDetailDao;
import com.entity.Td_tblPartyOrgDetail;
import com.service.inte.PartyOrgDetailServiceInte;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.List;

@Service
public class PartyOrgDetailServiceImpl implements PartyOrgDetailServiceInte {

    @Autowired
    private Td_tblPartyOrgDetailDao td_tblPartyOrgDetailDao;

    private LocalContainerEntityManagerFactoryBean entityManagerFactoryBean;

    @Override
    public Td_tblPartyOrgDetail getById(int id) {
        return td_tblPartyOrgDetailDao.getById(id);
    }

    @Override
    public List<Td_tblPartyOrgDetail> getAllByBranchId(int branchId) {
        return td_tblPartyOrgDetailDao.getLeaderByBranchId(branchId);
    }

    @Override
    @Transactional
    public void saveOrUpdate(Td_tblPartyOrgDetail td_tblPartyOrgDetail) {
        try {
            td_tblPartyOrgDetailDao.save(td_tblPartyOrgDetail);
        } catch (Exception e) {

        }

    }

    @Override
    @Transactional
    public int deleteByFd_BranchID(int branchId) {
        try {
            return td_tblPartyOrgDetailDao.deleteByFd_BranchID(branchId);
        } catch (Exception e) {

        }
        return 0;
    }

    @Override
    @Transactional
    public void saveAll(List<Td_tblPartyOrgDetail> partyOrgDetails) {
        td_tblPartyOrgDetailDao.saveAll(partyOrgDetails);
    }

    public int updateLeader(Td_tblPartyOrgDetail[] td_tblPartyOrgDetails, String[] leaderName) {
        StringBuilder sql = new StringBuilder();
        sql.append("insert into Td_tblPartyOrgDetail(fd_BranchID,fd_branchName,Fd_LoginID,fd_userName,fd_VLeaderName) values(");
        for (int i = 0; i < td_tblPartyOrgDetails.length; i++) {
            sql.append(td_tblPartyOrgDetails[i].getFd_BranchID() + ",'" + td_tblPartyOrgDetails[i].getFd_branchName() + "'," + td_tblPartyOrgDetails[i].getFd_LoginID() + ",'" + td_tblPartyOrgDetails[i].getFd_username() + "','" + leaderName[i] + "'");
        }
        System.out.println(sql);
        EntityManager entityManager = entityManagerFactoryBean.getNativeEntityManagerFactory().createEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        int i = 0;
        try {
            transaction.begin();
            i = entityManager.createQuery(sql.toString()).executeUpdate();
            transaction.commit();
        }catch (Exception e){
            transaction.rollback();
        }finally {
            return i;
        }
    }
}
